<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;


class Area extends  Model{

	protected $table='area_info';
    protected $_db_select = 'mysql_bgac';

    public $timestamps = false;
    //public $incrementing = false;
    protected $primaryKey = "id";

    //const UPDATED_AT = NULL;
    const CREATED_AT = NULL;

    const DB_FIELDS = 'id,name,areaId,ip,port,state,group_area,version,mc,roleLimit,op_state,area_physics,keepString';
    public static $area_state_type = [-1 => 'close', 0 => 'maintenance', 1=> 'hot', 2=> 'new', 3 => 'preopen', 4=> 'normal'];
    public static $area_mc = ['1000'=>'tianyu', '1001'=>'360','1002'=>'ali','1003'=>'baidu','1004'=>'yyb','1005'=>'xiaomi', '1006'=>'vivo','1007'=>'oppo','1008'=>'huawei','1009'=>'heepay',
        '1010' => 'brazil', '1011' => 'wanda','1012' =>'quick','1014' => 'klw',
        '2000' => 'ios', '2002' => 'GameCenter','2001' => 'facebook and google','2005' => 'poland',
    ];

    public static $open_time = 0;
    
    public static function areaAll($online = 1){
        $state = $online ? [1, 2, 4] :0;
        if ($state) {
            $data = \DB::connection('mysql_bgac')->table('area_info')->whereIn("state", $state)->get();
        } else {
            $data = \DB::connection('mysql_bgac')->table('area_info')->get();
        }
 
        $data = $data->toArray();
        return $data;
    }

    public static function areaSelectData($online = 1)
    {
        $list_data = Area::areaAll($online);
        $rtn = [];
        $rtn[0] = 'All Server';
        foreach($list_data as $obj){
            $rtn[$obj->areaId] = $obj->name;
        }

        if ($online == 0) {
            $rtn[-1] = 'No Server Select';
        }
        return $rtn;
    }

    
    // 获取游戏区域信息
    public static function areaInfo($area = 0){
        if (!$area) return [];
        $data = \DB::connection("mysql_bgac")->table("area_info")->where('areaId', $area)->orderBy("id", "DESC")->first();

        $ret = json_decode(json_encode($data, JSON_UNESCAPED_UNICODE), true);
                
        return $ret ?: [];
    }

    public function paginate()
    {
    	$perPage = Request::get('per_page', 20);

        $page = Request::get('page', 1);
        \Log::debug(__METHOD__, []);
        $start = ($page-1)*$perPage;

        $rw = \DB::connection($this->selectdb())->table($this->table)->where('deleted_at', 0)->orderBy("id", "desc")->skip($start)->take($perPage);
        self::SourceCondition($rw);
        $data = $rw->get();
        $data = $data->toArray();

        $total = \DB::connection($this->selectdb())->table($this->table)->where('deleted_at', 0)->count();

        // $data = json_decode($data, true);

        $list = static::hydrate($data);

        $paginator = new LengthAwarePaginator($list, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }
    public function selectdb($select = ''){
        if ($select) {
            return $this->_db_select = $select;
        }
        return $this->_db_select;
    }
    public function getConnectionName(){
        return $this->selectdb();
    }

    public static function assignByOut(&$one, $out){
        $flds = explode(',', self::DB_FIELDS);
        
        $oper_fix_online_max = false;

        foreach ($flds as $fld) {
            if ($one->roleLimit != $out['roleLimit']) {
                $oper_fix_online_max = true;
            }
            isset($out[$fld]) && $one->{$fld} = $out[$fld];
        }

        if ($one->id == 0) {
            !isset($one->chatIp) && $one->chatIp = $one->ip;
            !isset($one->mapIp) && $one->mapIp = $one->ip;
            !isset($one->loginIp) && $one->loginIp = $one->ip;
            unset($one->id);
        }
        $one->loginIp = $one->ip;
        $one->loginPort = $one->port;

        // 修改了人数上限
        if ($oper_fix_online_max && $one->areaId) {
            $area_id = $one->areaId;
            \App\Models\SendSocketToGame::SendAction(function($socket)use($one, $area_id){
                $data['msgid'] = $msgid ?:  \App\Service\MessageDef::http_plat_game_request;
                $data["area"] = intval($area_id); 
                $data['game_msgid'] = \App\Service\MessageDef::http_plat_max_online_request;
                $data["game_msg"] = [  
                    'max_online_num' => $one->roleLimit,
                    'op_able_new_reg' => $one->op_state & 1,
                    'op_able_under_age' => ($one->op_state & 2) ? 1: 0,
                ];
                $ret = $socket->send($data);
                \Log::debug('send game global varable!', [$ret, $data, $one->op_state]);
            });

        }
    }

    // 选择
    public static function RemoteBgsiSelectByArea($area_id)
    {
        if ($area_id == -1) {
            // 选择 日志公用的库
            \Config::set("database.connections.remote_bgsi", \Config::get('database.connections.mysql_bgsi'));
            \Config::set("database.connections.remote_bgsi.host", \env('DB_REMOTE_HOST'));
            \Config::set("database.connections.remote_bgsi.database", \env('DB_REMOTE_NAME'));
            \Config::set("database.connections.remote_bgsi.username", \env('DB_REMOTE_USER'));
            \Config::set("database.connections.remote_bgsi.password", \env('DB_REMOTE_PASS'));
            \Config::set("database.connections.remote_bgsi.port", \env('DB_REMOTE_PORT')?:3306);
            \Config::set("database.connections.remote_bgsi.unix_socket", null);
            \Log::debug(__METHOD__, [ \Config::get("database.connections.remote_bgsi")]);    
            return -1;
        }
        $conf = \Config::get("database.connections.remote_bgsi");
        // \Log::debug(__METHOD__, [$conf['area'], $area_id]);
        if ($conf['area'] == $area_id && $area_id > 0) {
            return;
        }
        $data = self::GetAreaExtendInfo($area_id);
        
        \Config::set("database.connections.remote_bgsi", \Config::get('database.connections.mysql_bgsi'));
        if (!$data["bgsi_ip"]){
            return 0;
        }
        // 选择具体的服务
        \Config::set("database.connections.remote_bgsi.host", $data["bgsi_ip"]);
        \Config::set("database.connections.remote_bgsi.database", $data['name']);
        \Config::set("database.connections.remote_bgsi.username", $data['login_name']);
        \Config::set("database.connections.remote_bgsi.password", $data['db_password']);
        \Config::set("database.connections.remote_bgsi.port", $data['port']?:3306);
        \Config::set("database.connections.remote_bgsi.unix_socket", null);
        \Config::set("database.connections.remote_bgsi.area", $area_id);

        self::$open_time = $data['open_time'];
        $conf = \Config::get("database.connections.remote_bgsi");
        
        \Log::debug(__METHOD__, [$area_id, $conf['host'],$conf['database']]);
        // \Log::stack([]);
        return $area_id;
    }

    public static function GetAreaExtendInfo($area)
    {
        if (empty($area)){
            return [];
        }
        $data = \DB::connection('mysql_bgac')->table('area_extend')->where("area", $area)->first();     
        return (array)$data;
    }

    public static function SourceCondition(&$rw)
    {
        $cond = Request::all();
        if ($cond['name'] && $cond['name'] != env('CP_AREA_PASSWD')){
            $rw->where("name", 'like', $cond["name"].'%');
        }
        if ($cond["areaId"] or $cond['area']){
            $rw->where("areaId", $cond['areaId'] ?: $cond['area']);
        }

    }

    public static function clearCache(){
        $url = env('APP_API_HOST') . env('APP_API_CLEAR_CACHE', '/api/clear');
        \App\Third\Curl::request($url, null, 'get');
    }

    // 获取服务器运行信息
    public static function getServerRunInfo($area, $ip = null) {
        
        
        $ip  ='http://'.($ip?: env('SERVER_INFO_IP', '127.0.0.1'));
        $port = env('SERVER_INFO_PORT', '8080');
        
        
        $url = $ip. ':'. $port. '/' . env('SERVER_INFO_GET');
        
        $url = \App\Service\Common::build_url_query($url, ['pwd'=>env('SERVER_INFO_PWD'), ]);
        
        $result = \App\Third\Curl::request($url, [], 'get');
        \Log::info('[AREA_SERVER_INFO]AREA['.$area.']', [$url, $result]);
        if ($result['code'] != 200) {

            return null;
        }

        if ( !$area) {
            return $result['data'];
        }
        foreach ( $result['data'] as $obj) {
            if ($obj['areaId'] == $area) {
                return $obj;
            }
        }
        return null;
    }

    public static function getServerRestartUrl($area, $op,$ip = null){
        $ip  ='http://'.($ip?: env('SERVER_INFO_IP', '127.0.0.1'));
        $port = env('SERVER_INFO_PORT', '8080');
        
        
        $url = $ip. ':'. $port. '/' . env('SERVER_INFO_PUT');
        return \App\Service\Common::build_url_query($url, ['pwd'=>env('SERVER_INFO_PWD'), 'areaId' => $area, 'op' => $op]);
    }

    // 根据逻辑服务id 获取 物理服id
    public static function getPhysicsArea($area) {
        $data = self::areaInfo($area);
        $ph = $data['area_physics'] ?: $data['areaId'];
        \Log::info("AREA[GET_PHYSICS_AREA]AREA[$area]PHYSIC_AREA[$ph]");
        return $ph;
    }

    // 获取当前所有有效的服务器 区号 集合
    public static function getValidAreas() {
        $list = \DB::connection("mysql_bgac")->table("area_info")->select('areaId', 'area_physics')->orderBy("id", "DESC")->get();

        $area_ids = [];
        foreach ($list as $obj) {
            $valid_area = $obj->area_physics ?: $obj->areaId;
            $area_ids[$valid_area] = $valid_area;
        }
        return $area_ids;
    }
}

